package com.ztjy.sys.controller;

import com.github.pagehelper.PageInfo;
import com.ztjy.annonation.MyLog;
import com.ztjy.bean.*;
import com.ztjy.purchase.biz.CBrandBiz;
import com.ztjy.sys.biz.*;
import com.ztjy.sys.biz.impl.SimpleCharVerifyCodeGenImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 用户管理
 */
@Controller
@RequestMapping("/sys/users")
@SessionAttributes({"depts", "provinces", "modules", "pmodules", "brands", "date"}) //currUser 作用范围HttpSession
public class UsersController {
    @Autowired
    private UsersBiz usersBiz;
    @Autowired
    private AreaBiz areaBiz;
    @Autowired
    private ModuleBiz moduleBiz;
    @Autowired
    private JobBiz jobBiz;
    @Autowired
    private CBrandBiz bbiz;
    @Autowired
    private PermissionBiz permissionBiz;

    //每次执行前会优先 将mid放入request范围
    @ModelAttribute
    public void initModuleData(HttpSession session) {
        session.removeAttribute("mid");
        session.setAttribute("mid", 25);
    }
    /**
     * 验证码
     *
     * @param request
     * @param response
     */
    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
        IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(114, 46);
            String code = verifyCode.getCode().toLowerCase();
            //将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 查询所有
     *
     * @param uname
     * @param upwd
     * @param model 回显内容
     * @return 结果视图页面
     */
    @RequestMapping("/login")
//    @MyLog("用户登录操作")
    public String doLogin(String uname, String verifycode, String upwd, Model model, HttpSession session) {
        //从session中获取验证码
        String verifyCode = session.getAttribute("VerifyCode").toString();
        if (!verifyCode.equals(verifycode.toLowerCase())) {
            model.addAttribute("msg", "验证码错误！");
            return "forward:/login.html";
        }

        Users user = usersBiz.login(uname, upwd);
        if (user != null) {//成功
            session.setAttribute("currUser", user);
            List<Dept> depts = usersBiz.findAllDept();//查询所有部门信息
            model.addAttribute("depts", depts);
            //查询所有品牌
            List<CBrand> allCBrand = bbiz.findAllCBrand();
            model.addAttribute("brands", allCBrand);
            //默认时间
            Date date = new Date();
            model.addAttribute("date", date);

            //查询所有省份
            List<Province> provinceAll = areaBiz.findProvinceAll();
            model.addAttribute("provinces", provinceAll);
            //左侧边栏 状态是1
            //List<Module> modules = moduleBiz.selectAllModule("",0);
            //显示所有父模块 状态是1
            // List<Module> allParentModule = moduleBiz.findAllParentModule(1);

            //用户职位
            Integer jobId = user.getJobId();
            //显示所有父模块 状态是1
            List<Module> allParentModule = permissionBiz.findMoudleByJob(jobId, 1, 1);
            //显示所有模块 状态是1
            List<Module> modules = permissionBiz.findMoudleByJob(jobId, 1, 0);
            model.addAttribute("modules", modules);
            model.addAttribute("pmodules", allParentModule);
            return "redirect:/main.html";
        } else {//失败
            model.addAttribute("msg", "用户名或密码错误！");
            return "forward:/login.html";
        }

    }

    /**
     * 退出  清除HttpSession
     *
     * @return
     */
    @RequestMapping("/logout")
    public String doLogOut(HttpSession session) {
//        session.removeAttribute("currUser");//清除指定的currUser
        session.invalidate();//清除所有session
        return "redirect:/login.html";
    }

    @MyLog(value = "查询所有用户操作")  //这里添加了AOP的自定义注解
    @RequestMapping("/userall")
    public String userList(Model model, Users users, @RequestParam(value = "pageno", defaultValue = "1") Integer pageNo) {
        Integer pageSize = 6;
        PageInfo<Users> pageInfo = usersBiz.findAllPage(users, pageNo, pageSize);
        model.addAttribute("upinfo", pageInfo);
        model.addAttribute("user", users);
        return "forward:/sys/users/userList.html";
    }

    @MyLog(value = "添加了用户操作")  //这里添加了AOP的自定义注解
    @RequestMapping("/adduser")
    public String addUser(Users user, Model model) {
        boolean flag = usersBiz.addUsers(user);
        if (flag) {
            return "redirect:/sys/users/userall";
        } else {
            return "forward:/sys/users/userAdd.html";
        }
    }

    @RequestMapping("/goUpdate/{uId}")
    public String updaUser(@PathVariable("uId") Integer uId, Model model) {
        Users users = usersBiz.detailsUsers(uId);
        model.addAttribute("user", users);
        return "forward:/sys/users/userUpdate.html";
    }

    @MyLog(value = "修改了用户操作")
    @RequestMapping("/doUpdate")
    public String doUpdate(Users users, Model model) {
        boolean flag = usersBiz.updateUsers(users);
        if (flag) {
            return "redirect:/sys/users/userall";
        } else {
            return "forward:/sys/users/userUpdate.html";
        }
    }

    /**
     * 修改状态
     */
    @RequestMapping("/updatestate")
    public String updateState(Model model, Integer id, Integer changestate) {
        Users users = usersBiz.detailsUsers(id);
        users.setStatusId(changestate);
        Boolean flag = usersBiz.updateUsers(users);
        return "redirect:/sys/users/userall";
    }


    //详情
    @RequestMapping("/details/{uId}")
    public String detailsUsers(@PathVariable("uId") Integer uId, Model model) {
        Users users = usersBiz.detailsUsers(uId);
        model.addAttribute("user", users);
        return "forward:/sys/users/userView.html";
    }
}
